package com.requiem.hist_group_manage_springboot.common;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.requiem.hist_group_manage_springboot.constants.SystemConstants;
import com.requiem.hist_group_manage_springboot.exception.iException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public boolean preHandle(@org.jetbrains.annotations.NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        if (HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return true; // 直接放行
        }
        String auth_token = request.getHeader("auth-token");
        if (auth_token == null || auth_token.isEmpty() || auth_token.equals("null")) {
            System.out.println("auth-token is :" + auth_token);
            throw new iException(SystemConstants.UNAUTHORIZED, SystemConstants.UNAUTHORIZED_MSG);
        }
        DecodedJWT decodedJWT;
        try {
            decodedJWT = jwtUtil.verifyToken(auth_token);
        } catch (Exception e) {
            throw new iException(SystemConstants.USERNAME_TOKEN_ERROR, e.getMessage());
        }
        request.setAttribute("user_id", decodedJWT.getClaim("user_id").asInt());
        return true;
    }
}
